<?php

namespace App\Jobs;

use App\Models\Article;
use App\Models\Comment;
use App\Models\Subscribe;
use App\Services\PublishTemplateService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class CommentSubscribe implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $comment_id;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($comment_id)
    {
        $this->comment_id = $comment_id;
    }

    /**
     * Execute the job.
     * @link https://shimo.im/mindmaps/y6ydprxxxJKCggPx/
     * @return void
     */
    public function handle()
    {
        $field = ['nickname', 'openid'];
        $info = Comment::withCertain('user', $field)
            ->withCertain('entity_user', $field)->find($this->comment_id);
        if (!$info)
            return;

        $subscribe = Subscribe::where('user_id', $info->entity_user->id)->where('template_id', Subscribe::TEMPLATE_COMMENT)->orderBy('id', 'asc')->first();
        if ($subscribe)
            $subscribe->delete();

        $article = Article::find($info->entity_id);
        $service = new PublishTemplateService();
        $service->comment($info->entity_user->openid, $article->title, $info->user->nickname, $article->id, $article->type);
    }
}
